package yang.learn.controller;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.context.annotation.ComponentScan;

import java.io.IOException;

//目前拦截所有请求，可以根据需求修url匹配样式
@WebFilter("*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        //设置响应编码，防止中文乱码
        req.setCharacterEncoding("UTF-8");
        res.setCharacterEncoding("UTF-8");
        //获取头部信息中的token
        String token = null;
        String admin_token = null;
        if(req.getCookies() != null) {
            for (Cookie cookie : req.getCookies()) {
                if ("uuid".equals(cookie.getName())) token = cookie.getValue();
                if ("admin_uuid".equals(cookie.getName())) admin_token = cookie.getValue();
            }
        }
        if(token == null || "".equals(token)) {//用户未登录
            req.setAttribute("login_result","fail");
            chain.doFilter(req, res);
            return;
        }
        //获取session
        HttpSession session = req.getSession();
        //从session中获取服务端存储token
        String tokenServer = (String) session.getAttribute("token");
        if(!token.equals(tokenServer)) {//如果请求头中token与服务端token失配
            req.setAttribute("login_result", "timeout");
            chain.doFilter(req, res);
            return;
        }
        if(admin_token != null && admin_token.equals(tokenServer)) {
            req.setAttribute("login_result", "admin_success");
            chain.doFilter(req, res);
            return;
        }
        /*用户token匹配成功*/
        req.setAttribute("login_result", "success");
        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {

    }
}
